package com.ai.aiagent.chatmemory;

import com.ai.aiagent.repository.MysqlChatMemoryRepository;
import com.ai.aiagent.service.MysqlChatMemoryService;
import com.ai.aiagent.service.impl.MysqlChatMemoryServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 基于文件持久化的对话记忆，即使应用重启，也会根据回话id找到之前的对话记录
 */
@Component
public class MysqlChatMemory implements ChatMemory {

    @Autowired
    private MysqlChatMemoryService mysqlChatMemoryServiceImpl;


    public MysqlChatMemory() {
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        List<Message> createConversation = null;
        try {
            createConversation = mysqlChatMemoryServiceImpl.get(Long.valueOf(conversationId));
            createConversation.addAll(messages);
            mysqlChatMemoryServiceImpl.save(Long.valueOf(conversationId), "user", createConversation);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Message> get(String conversationId) {
        try {
            return mysqlChatMemoryServiceImpl.get(Long.valueOf(conversationId));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void clear(String conversationId) {
        mysqlChatMemoryServiceImpl.clear(Long.valueOf(conversationId));
    }
}
